#include <iostream>

#include "evnetplus/event_loop_thread.h"
#include "evnetplus/event_loop_thread_pool.h"
#include "evnetplus/event_watcher.h"
#include "evnetplus/udp_client_plus.h"

using namespace evnetplus;
using namespace udp;

#define REMOTE_ADDRESS "192.168.0.224:8080"

class ExampleClient : public UDPClientPlus {
public:
    explicit ExampleClient(EventLoop* loop,
                           const std::string& remote_addr,
                           const std::string& name)
        : UDPClientPlus(loop, remote_addr, name) {}
    virtual ~ExampleClient() {}

    virtual void onReceive(const MessagePtr& msg) override {
        SendMessage(msg);
    }

    virtual void onTimerHandle() override {
        sendMessage(Slice("This is a evnetplus async udp communication example! " + std::to_string(call_timece++)));
    }

private:
    uint32_t call_timece = 0;
};

int main(int argc, char const *argv[])
{
    EventLoopThread loopthread;
    loopthread.Start(true);

    std::shared_ptr<ExampleClient> example_client = std::make_shared<ExampleClient>(
            loopthread.loop(), REMOTE_ADDRESS, "ExampleClient");
    if (nullptr == example_client) {
        std::cerr << "Create failed" << std::endl;
        loopthread.Stop(true);
        return -1;
    }
    example_client->create();

    bool bEnableStop = false;
    SignalEventWatcher signalWatcher(SIGINT, loopthread.loop(), [&bEnableStop](){
        std::cout << "atched signal" << std::endl;
        bEnableStop = true;
    });
    signalWatcher.Init();
    signalWatcher.AsyncWait();

    while (!bEnableStop) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }

    example_client->destroy();
    loopthread.Stop(true);

    return 0;
}
